{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {
    "collapsed": false
   },
   "source": [
    "## Interpretability - Explanation Dashboard\n",
    "\n",
    "In this example, similar to the \"Interpretability - Tabular SHAP explainer\" notebook, we use Kernel SHAP to explain a tabular classification model built from the Adults Census dataset and then visualize the explanation in the ExplanationDashboard from https://github.com/microsoft/responsible-ai-widgets.\n",
    "\n",
    "First we import the packages and define some UDFs we will need later."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "%pip install raiwidgets itsdangerous==2.0.1 interpret-community"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "from IPython.terminal.interactiveshell import TerminalInteractiveShell\n",
    "from synapse.ml.explainers import *\n",
    "from pyspark.ml import Pipeline\n",
    "from pyspark.ml.classification import LogisticRegression\n",
    "from pyspark.ml.feature import StringIndexer, OneHotEncoder, VectorAssembler\n",
    "from pyspark.ml.functions import vector_to_array\n",
    "from pyspark.sql.types import *\n",
    "from pyspark.sql.functions import *\n",
    "import pandas as pd\n",
    "\n",
    "vec_access = udf(lambda v, i: float(v[i]), FloatType())"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "collapsed": false
   },
   "source": [
    "Now let's read the data and train a simple binary classification model."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "df = spark.read.parquet(\n",
    "    \"wasbs://publicwasb@mmlspark.blob.core.windows.net/AdultCensusIncome.parquet\"\n",
    ").cache()\n",
    "\n",
    "labelIndexer = StringIndexer(\n",
    "    inputCol=\"income\", outputCol=\"label\", stringOrderType=\"alphabetAsc\"\n",
    ").fit(df)\n",
    "print(\"Label index assigment: \" + str(set(zip(labelIndexer.labels, [0, 1]))))\n",
    "\n",
    "training = labelIndexer.transform(df)\n",
    "display(training)\n",
    "categorical_features = [\n",
    "    \"workclass\",\n",
    "    \"education\",\n",
    "    \"marital-status\",\n",
    "    \"occupation\",\n",
    "    \"relationship\",\n",
    "    \"race\",\n",
    "    \"sex\",\n",
    "    \"native-country\",\n",
    "]\n",
    "categorical_features_idx = [col + \"_idx\" for col in categorical_features]\n",
    "categorical_features_enc = [col + \"_enc\" for col in categorical_features]\n",
    "numeric_features = [\n",
    "    \"age\",\n",
    "    \"education-num\",\n",
    "    \"capital-gain\",\n",
    "    \"capital-loss\",\n",
    "    \"hours-per-week\",\n",
    "]\n",
    "\n",
    "strIndexer = StringIndexer(\n",
    "    inputCols=categorical_features, outputCols=categorical_features_idx\n",
    ")\n",
    "onehotEnc = OneHotEncoder(\n",
    "    inputCols=categorical_features_idx, outputCols=categorical_features_enc\n",
    ")\n",
    "vectAssem = VectorAssembler(\n",
    "    inputCols=categorical_features_enc + numeric_features, outputCol=\"features\"\n",
    ")\n",
    "lr = LogisticRegression(featuresCol=\"features\", labelCol=\"label\", weightCol=\"fnlwgt\")\n",
    "pipeline = Pipeline(stages=[strIndexer, onehotEnc, vectAssem, lr])\n",
    "model = pipeline.fit(training)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "collapsed": false
   },
   "source": [
    "After the model is trained, we randomly select some observations to be explained."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "explain_instances = (\n",
    "    model.transform(training).orderBy(rand()).limit(5).repartition(200).cache()\n",
    ")\n",
    "display(explain_instances)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "collapsed": false
   },
   "source": [
    "We create a TabularSHAP explainer, set the input columns to all the features the model takes, specify the model and the target output column we are trying to explain. In this case, we are trying to explain the \"probability\" output which is a vector of length 2, and we are only looking at class 1 probability. Specify targetClasses to `[0, 1]` if you want to explain class 0 and 1 probability at the same time. Finally we sample 100 rows from the training data for background data, which is used for integrating out features in Kernel SHAP."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "shap = TabularSHAP(\n",
    "    inputCols=categorical_features + numeric_features,\n",
    "    outputCol=\"shapValues\",\n",
    "    numSamples=5000,\n",
    "    model=model,\n",
    "    targetCol=\"probability\",\n",
    "    targetClasses=[1],\n",
    "    backgroundData=broadcast(training.orderBy(rand()).limit(100).cache()),\n",
    ")\n",
    "\n",
    "shap_df = shap.transform(explain_instances)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "collapsed": false
   },
   "source": [
    "Once we have the resulting dataframe, we extract the class 1 probability of the model output, the SHAP values for the target class, the original features and the true label. Then we convert it to a pandas dataframe for visualization.\n",
    "For each observation, the first element in the SHAP values vector is the base value (the mean output of the background dataset), and each of the following element is the SHAP values for each feature."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "shaps = (\n",
    "    shap_df.withColumn(\"probability\", vec_access(col(\"probability\"), lit(1)))\n",
    "    .withColumn(\"shapValues\", vector_to_array(col(\"shapValues\").getItem(0)))\n",
    "    .select(\n",
    "        [\"shapValues\", \"probability\", \"label\"] + categorical_features + numeric_features\n",
    "    )\n",
    ")\n",
    "\n",
    "shaps_local = shaps.toPandas()\n",
    "shaps_local.sort_values(\"probability\", ascending=False, inplace=True, ignore_index=True)\n",
    "pd.set_option(\"display.max_colwidth\", None)\n",
    "shaps_local"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "collapsed": false
   },
   "source": [
    "We can visualize the explanation in the [interpret-community format](https://github.com/interpretml/interpret-community) in the ExplanationDashboard from https://github.com/microsoft/responsible-ai-widgets/"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "\n",
    "features = categorical_features + numeric_features\n",
    "features_with_base = [\"Base\"] + features\n",
    "\n",
    "rows = shaps_local.shape[0]\n",
    "\n",
    "local_importance_values = shaps_local[[\"shapValues\"]]\n",
    "eval_data = shaps_local[features]\n",
    "true_y = np.array(shaps_local[[\"label\"]])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "list_local_importance_values = local_importance_values.values.tolist()\n",
    "converted_importance_values = []\n",
    "bias = []\n",
    "for classarray in list_local_importance_values:\n",
    "    for rowarray in classarray:\n",
    "        converted_list = rowarray.tolist()\n",
    "        bias.append(converted_list[0])\n",
    "        # remove the bias from local importance values\n",
    "        del converted_list[0]\n",
    "        converted_importance_values.append(converted_list)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "collapsed": false
   },
   "source": [
    "When running Synapse Analytics, please follow instructions here [Package management - Azure Synapse Analytics | Microsoft Docs](https://docs.microsoft.com/en-us/azure/synapse-analytics/spark/apache-spark-azure-portal-add-libraries) to install [\"raiwidgets\"](https://pypi.org/project/raiwidgets/) and [\"interpret-community\"](https://pypi.org/project/interpret-community/) packages."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "from interpret_community.adapter import ExplanationAdapter\n",
    "\n",
    "adapter = ExplanationAdapter(features, classification=True)\n",
    "global_explanation = adapter.create_global(\n",
    "    converted_importance_values, eval_data, expected_values=bias\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "# view the global importance values\n",
    "global_explanation.global_importance_values"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "# view the local importance values\n",
    "global_explanation.local_importance_values"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "class wrapper(object):\n",
    "    def __init__(self, model):\n",
    "        self.model = model\n",
    "\n",
    "    def predict(self, data):\n",
    "        sparkdata = spark.createDataFrame(data)\n",
    "        return (\n",
    "            model.transform(sparkdata)\n",
    "            .select(\"prediction\")\n",
    "            .toPandas()\n",
    "            .values.flatten()\n",
    "            .tolist()\n",
    "        )\n",
    "\n",
    "    def predict_proba(self, data):\n",
    "        sparkdata = spark.createDataFrame(data)\n",
    "        prediction = (\n",
    "            model.transform(sparkdata)\n",
    "            .select(\"probability\")\n",
    "            .toPandas()\n",
    "            .values.flatten()\n",
    "            .tolist()\n",
    "        )\n",
    "        proba_list = [vector.values.tolist() for vector in prediction]\n",
    "        return proba_list"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "# view the explanation in the ExplanationDashboard\n",
    "from raiwidgets import ExplanationDashboard\n",
    "\n",
    "ExplanationDashboard(\n",
    "    global_explanation, wrapper(model), dataset=eval_data, true_y=true_y\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "application/vnd.databricks.v1+cell": {
     "inputWidgets": {},
     "nuid": "8f22fceb-0fc0-4a86-a0ca-2a7b47b4795a",
     "showTitle": false,
     "title": ""
    }
   },
   "source": [
    "Your results will look like:\n",
    "\n",
    "<img src=\"https://mmlspark.blob.core.windows.net/graphics/rai-dashboard.png\" style=\"float: right;\"/>"
   ]
  }
 ],
 "metadata": {
  "application/vnd.databricks.v1+notebook": {
   "dashboards": [],
   "language": "python",
   "notebookMetadata": {
    "pythonIndentUnit": 2
   },
   "notebookName": "Interpretability - Tabular SHAP explainer",
   "notebookOrigID": 4343954975413564,
   "widgets": {}
  },
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.9"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
